package com.cloud.system.common.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.cloud.system.common.result.QkMenuItem;

/**
 * 树算法工具类
 * 
 * @author taominglong
 *
 */
public class MenuItemHelper {

	/**
	 * 递归将List封装为树节点
	 * 
	 * @param elements
	 * @return
	 */
	public static final QkMenuItem[] buildList2Tree(List<QkMenuItem> elements) {
		List<QkMenuItem> roots = new ArrayList<QkMenuItem>();
		for (QkMenuItem node : elements) {
			if (node.isRootFlag()) {
				roots.add(node);
			}
		}
		@SuppressWarnings("unchecked")
		List<QkMenuItem> notRoots = (List<QkMenuItem>) CollectionUtils.subtract(elements, roots);
		for (QkMenuItem root : roots) {
			List<QkMenuItem> children = findChildren(root, notRoots);
			if(null == children || children.size() == 0){
				root.setItems(null);
			}else{
				root.setItems(children);
			}
		}
		return roots.toArray(new QkMenuItem[roots.size()]);
	}

	private static List<QkMenuItem> findChildren(QkMenuItem root, List<QkMenuItem> allNodes) {
		List<QkMenuItem> children = new ArrayList<QkMenuItem>();
		for (QkMenuItem node : allNodes) {
			if (node.getSeniorId().equals(root.getId())) {
				children.add(node);
			}
		}
		@SuppressWarnings("unchecked")
		List<QkMenuItem> notChildren = (List<QkMenuItem>) CollectionUtils.subtract(allNodes, children);
		for (QkMenuItem child : children) {
			List<QkMenuItem> c = findChildren(child, notChildren);
			if (c.size() < 1) { //叶子节点，不显示展开操作按钮
				child.setItems(null);
			}else{
				child.setItems(c);
			}
		}
		return children;
	}
}
